package com.pengtu.web.receive.wt05;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.Constants;
import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.app.User;
import com.pengtu.entity.history.HistoryProject;
import com.pengtu.entity.project.Relationship;
import com.pengtu.entity.receive.Entrust;
import com.pengtu.entity.receive.Trialwt05;
import com.pengtu.entity.trial.Order;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.service.NumberManager;
import com.pengtu.service.history.HistoryProjectManager;
import com.pengtu.service.project.RelationshipManager;
import com.pengtu.service.quality.FprojectManager;
import com.pengtu.service.receive.TrialCommonManager;
import com.pengtu.service.trial.TrialManager;
import com.pengtu.utils.web.ControlHelpUtil;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

@Results({
		@Result(name = BaseActionSupport.RELOAD, location = "${ctx}/receive/wt05/trialwt05.action", type = "redirect"),
		@Result(name = "part0", location = "${ctx}/receive/wt05/trialwt05!login.action?id=${id}", type = "redirect"),
		@Result(name = Constants.LAST, location = "${ctx}/receive/wt05/trialwt05!taketask.action?id=${id}&status=${status}&taskid=${taskid}", type = "redirect"),
		@Result(name = Constants.OWN, location = "${ctx}/receive/entrust/history.action?key=${id}&pngFileName=entrust.png", type = "redirect"),
		@Result(name = "part1", location = "${ctx}/receive/wt05/trialwt05!first.action?id=${id}", type = "redirect") })
public class Trialwt05Action extends BaseActionSupport<Entrust> {

	/**
	 * serialVersionUID:TODO
	 * 
	 * @since 1.0.0
	 */

	private static final long serialVersionUID = 1L;
	private Relationship relationship;// 工程
	private Order order;// 检验项目依据标准
	private String[] ord;
	private Entrust entrust;
	private List<Trialwt05> trialwt05s;
	private List<Trialwt05> oldTrialwt05s;
	private Trialwt05 trialwt05;
	private TrialCommonManager trialCommonManager;
	private RelationshipManager relationshipManager;
	private TrialManager trialManager;
	private NumberManager numberManager;
	private String relationId;
	private String id;
	private Page<Entrust> page = new Page<Entrust>(10);
	private FprojectManager fprojectManager;
	private String taskid;
	private HistoryProjectManager historyProjectManager;
	private String status;
	private User user = SpringSecurityUtils.getCurrentUser();

	@Override
	public Entrust getModel() {
		// TODO Auto-generated method stub
		return entrust;
	}

	@Override
	public String list() throws Exception {
		QueryFilter filters = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		// 设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("checkdate");
			page.setOrder(Page.DESC);
		}
		filters.addFilter("trialType", "WT05");
		page = trialCommonManager.findByEntrustPage(page, filters);
		System.out.println(page.getResult().size());
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		if (StringUtils.isEmpty(id)) {
			entrust.setEntrustNum(numberManager.getRandomNum());
		} else {
			Set<Order> ll = entrust.getOrders();
			relationId = entrust.getRelationship().getId();
			Iterator<Order> ls = ll.iterator();
			if (ls.hasNext()) {
				Order order = ls.next();
				Set<Trialwt05> oldTrialwt05s = order.getTrialwt05s();
				Struts2Utils.getRequest().setAttribute("oldTrialwt05s",
						oldTrialwt05s);
			}
		}
		return INPUT;
	}

	public String view() throws Exception {
		if (StringUtils.isEmpty(id)) {
			entrust.setEntrustNum(numberManager.getRandomNum());
		} else {
			Set<Order> ll = entrust.getOrders();
			relationId = entrust.getRelationship().getId();
			Iterator<Order> ls = ll.iterator();
			if (ls.hasNext()) {
				Order order = ls.next();
				Set<Trialwt05> oldTrialwt05s = order.getTrialwt05s();
				Struts2Utils.getRequest().setAttribute("oldTrialwt05s",
						oldTrialwt05s);
			}
		}
		return VIEW;
	}

	public void prepareView() throws Exception {
		prepareModel();
	}

	@Override
	public String save() throws Exception {

		if (StringUtils.isNotEmpty(id)) {
			trialCommonManager.deleteOrderTrialwt05sByEntrust(entrust);
		}
		if (StringUtils.isNotEmpty(relationId)) {
			relationship = relationshipManager.findByPropertyName("id",
					relationId);
			relationship.setWitnesses(entrust.getWitnesses());
			relationship.setWphone(entrust.getWphone());
			relationship.setOperations(entrust.getOperations());
			relationship.setOphone(entrust.getOphone());
			relationship.setCheckpeople(entrust.getCheckpeople());
			relationship.setCheckphone(entrust.getCheckphone());
			relationshipManager.saveRelationship(relationship);

			entrust.setTrialType("WT05");
			entrust.setRelationship(relationship);
			trialCommonManager.saveEntrust(entrust);

			Set<Trialwt05> pp = new HashSet<Trialwt05>();
			if (trialwt05s != null) {
				for (int i = 0; i < trialwt05s.size(); i++) {
					if (trialwt05s.get(i) != null) {
						pp.add(trialwt05s.get(i));
					}
				}
			}
			if (oldTrialwt05s != null) {
				for (int i = 0; i < oldTrialwt05s.size(); i++) {
					if (oldTrialwt05s.get(i) != null) {
						pp.add(oldTrialwt05s.get(i));
					}
				}
			}
			trialCommonManager.saveTrialwt05All(pp);
			for (int j = 0; j < ord.length; j++) {
				Order order = new Order();
				order.setType(ord[j]);
				order.setStandard(entrust.getStandard());
				order.setTrialtype("WT05");
				order.setReportcode(numberManager.getRandomNum());
				order.setEntrust(entrust);
				order.setTrialwt05s(pp);
				trialManager.saveOrder(order);
			}
		}
		return RELOAD;
	}

	/**
	 * 流程提交保存 save1: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String save1() throws Exception {
		if (StringUtils.isNotEmpty(relationId)) {
			relationship = relationshipManager.findByPropertyName("id",
					relationId);
			relationship.setWitnesses(entrust.getWitnesses());
			relationship.setWphone(entrust.getWphone());
			relationship.setOperations(entrust.getOperations());
			relationship.setOphone(entrust.getOphone());
			relationship.setCheckpeople(entrust.getCheckpeople());
			relationship.setCheckphone(entrust.getCheckphone());
			relationshipManager.saveRelationship(relationship);

			entrust.setTrialType("WT05");
			entrust.setRelationship(relationship);
			trialCommonManager.saveEntrust(entrust);
			Set<Trialwt05> pp = new HashSet<Trialwt05>();
			if (trialwt05s != null) {
				for (int i = 0; i < trialwt05s.size(); i++) {
					if (trialwt05s.get(i) != null) {
						pp.add(trialwt05s.get(i));
					}
				}
			}
			if (oldTrialwt05s != null) {
				for (int i = 0; i < oldTrialwt05s.size(); i++) {
					if (oldTrialwt05s.get(i) != null) {
						pp.add(oldTrialwt05s.get(i));
					}
				}
			}
			trialCommonManager.saveTrialwt05All(pp);
			for (int j = 0; j < ord.length; j++) {
				Order order = new Order();
				order.setType(ord[j]);
				order.setStandard(entrust.getStandard());
				order.setTrialtype("WT05");
				order.setReportcode(numberManager.getRandomNum());
				order.setEntrust(entrust);
				order.setTrialwt05s(pp);
				trialManager.saveOrder(order);
			}
		}
		return "part0";
	}

	public void prepareSave1() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	public String login() throws Exception {
		return LOGIN;
	}

	public void prepareLogin() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	public String assign() throws Exception {
		return Constants.ASSIGN;
	}

	public void prepareAssign() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	/**
	 * 启动流程 start: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String start() throws Exception {
		String deploymentId = fprojectManager.getByKey("entrust")
				.getDeploymentId();
		String key = Struts2Utils.getParameter("key");
		String value = Struts2Utils.getParameter("value");
		String key1 = Struts2Utils.getParameter("key1");
		String value1 = Struts2Utils.getParameter("value1");
		Map<String, Object> variables = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(key)) {
			variables.put(key, value);
		}
		if (StringUtils.isNotEmpty(key1)) {
			variables.put(key1, value1);
		}
		variables.put("entrustId", id);
		trialCommonManager.start(id, deploymentId, "entrust05", variables);
		trialCommonManager.saveEntrust(entrust);
		return RELOAD;
	}

	public void prepareStart() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	/**
	 * 业务转发 judge: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String judge() throws Exception {
		taskid = trialCommonManager.isPersonalTasks(user, id, "entrustId");
		if (StringUtils.isEmpty(status)) {
			status = entrust.getStatus();
		}
		if (StringUtils.isNotEmpty(taskid)) {
			return Constants.LAST;
		}
		return Constants.OWN;
	}

	public void prepareJudge() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	/**
	 * 接受任务 taketask: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String taketask() throws Exception {
		HistoryProject historyProject = historyProjectManager.get(taskid);
		String activityName = trialCommonManager.getTask(taskid)
				.getActivityName();
		if (historyProject == null) {
			historyProject = new HistoryProject();
			historyProject.setKey(id);
			historyProject.setUserName(user.getUserName());
			historyProject.setStatus("000" + status);
			historyProject.setStartDate(new Date());
			historyProject.setTaskId(taskid);
			historyProject.setActivityName(activityName);
		}
		try {
			trialCommonManager.takeTask(taskid, user);
			historyProjectManager.save(historyProject);
		} catch (org.jbpm.api.JbpmException e) {
			historyProjectManager.save(historyProject);
		}
		ControlHelpUtil.setObjectToSession("taskid", taskid);
		if (StringUtils.equals(activityName, "收样复核")) {
			return "part1";
		}
		return null;
	}

	public void prepareTaketask() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	/**
	 * 复核页面 first: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String first() throws Exception {
		return "first";
	}

	public void prepareFirst() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	/**
	 * 任务提交 submit: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String submit() throws Exception {
		String outcome = Struts2Utils.getParameter("outcome");
		String view = Struts2Utils.getParameter("view");
		String key = Struts2Utils.getParameter("key");
		String value = Struts2Utils.getParameter("value");
		String key1 = Struts2Utils.getParameter("key1");
		String value1 = Struts2Utils.getParameter("value1");
		String count = Struts2Utils.getParameter("count");
		String leader = Struts2Utils.getParameter("leader");
		Map<String, Object> variables = new HashMap<String, Object>();
		HistoryProject historyProject = historyProjectManager.get(taskid);
		historyProject.setEndDate(new Date());
		historyProject.setMessage(user.getName() + "：" + view);
		if (StringUtils.isNotEmpty(key)) {
			variables.put(key, value);
		}
		if (StringUtils.isNotEmpty(key1)) {
			variables.put(key1, value1);
		}
		if (StringUtils.isNotEmpty(count)) {
			variables.put("count", count);
		}
		if (StringUtils.isNotEmpty(leader)) {
			variables.put("leader", leader);
		}
		trialCommonManager.completeTask(taskid, outcome, variables);
		trialCommonManager.saveEntrust(entrust);
		historyProjectManager.save(historyProject);
		return RELOAD;
	}

	public void prepareSubmit() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	public String recheck() throws Exception {
		QueryFilter filters = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		// 设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("checkdate");
			page.setOrder(Page.DESC);
		}
		filters.addFilter("trialType", "WT05");
		page = trialCommonManager.findByEntrustPage(page, filters);
		System.out.println(page.getResult().size());
		return "recheck";
	}
	
	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			entrust = trialCommonManager.FindByProEntrust("id", id);
		} else {
			entrust = new Entrust();
		}
	}

	/**
	 * relationship
	 * 
	 * @return the relationship
	 * @since 1.0.0
	 */

	public Relationship getRelationship() {
		return relationship;
	}

	/**
	 * @param relationship
	 *            the relationship to set
	 */
	public void setRelationship(Relationship relationship) {
		this.relationship = relationship;
	}

	/**
	 * order
	 * 
	 * @return the order
	 * @since 1.0.0
	 */

	public Order getOrder() {
		return order;
	}

	/**
	 * @param order
	 *            the order to set
	 */
	public void setOrder(Order order) {
		this.order = order;
	}

	/**
	 * entrust
	 * 
	 * @return the entrust
	 * @since 1.0.0
	 */

	public Entrust getEntrust() {
		return entrust;
	}

	/**
	 * @param entrust
	 *            the entrust to set
	 */
	public void setEntrust(Entrust entrust) {
		this.entrust = entrust;
	}

	/**
	 * trialwt05s
	 * 
	 * @return the trialwt05s
	 * @since 1.0.0
	 */

	public List<Trialwt05> getTrialwt05s() {
		return trialwt05s;
	}

	/**
	 * @param trialwt05s
	 *            the trialwt05s to set
	 */
	public void setTrialwt05s(List<Trialwt05> trialwt05s) {
		this.trialwt05s = trialwt05s;
	}

	/**
	 * trialwt05
	 * 
	 * @return the trialwt05
	 * @since 1.0.0
	 */

	public Trialwt05 getTrialwt05() {
		return trialwt05;
	}

	/**
	 * @param trialwt05
	 *            the trialwt05 to set
	 */
	public void setTrialwt05(Trialwt05 trialwt05) {
		this.trialwt05 = trialwt05;
	}

	public String[] getOrd() {
		return ord;
	}

	/**
	 * @param ord
	 *            the ord to set
	 */
	public void setOrd(String[] ord) {
		this.ord = ord;
	}

	/**
	 * @param trialCommonManager
	 *            the trialCommonManager to set
	 */
	@Autowired
	public void setTrialCommonManager(TrialCommonManager trialCommonManager) {
		this.trialCommonManager = trialCommonManager;
	}

	/**
	 * @param relationshipManager
	 *            the relationshipManager to set
	 */
	@Autowired
	public void setRelationshipManager(RelationshipManager relationshipManager) {
		this.relationshipManager = relationshipManager;
	}

	/**
	 * @param trialManager
	 *            the trialManager to set
	 */
	@Autowired
	public void setTrialManager(TrialManager trialManager) {
		this.trialManager = trialManager;
	}

	/**
	 * relationId
	 * 
	 * @return the relationId
	 * @since 1.0.0
	 */

	public String getRelationId() {
		return relationId;
	}

	/**
	 * @param relationId
	 *            the relationId to set
	 */
	public void setRelationId(String relationId) {
		this.relationId = relationId;
	}

	/**
	 * page
	 * 
	 * @return the page
	 * @since 1.0.0
	 */

	public Page<Entrust> getPage() {
		return page;
	}

	/**
	 * @param page
	 *            the page to set
	 */
	public void setPage(Page<Entrust> page) {
		this.page = page;
	}

	/**
	 * id
	 * 
	 * @return the id
	 * @since 1.0.0
	 */

	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @param numberManager
	 *            the numberManager to set
	 */
	@Autowired
	public void setNumberManager(NumberManager numberManager) {
		this.numberManager = numberManager;
	}

	/**
	 * oldTrialwt05s
	 * 
	 * @return the oldTrialwt05s
	 * @since 1.0.0
	 */

	public List<Trialwt05> getOldTrialwt05s() {
		return oldTrialwt05s;
	}

	/**
	 * @param oldTrialwt05s
	 *            the oldTrialwt05s to set
	 */
	public void setOldTrialwt05s(List<Trialwt05> oldTrialwt05s) {
		this.oldTrialwt05s = oldTrialwt05s;
	}

	/**
	 * taskid
	 * 
	 * @return the taskid
	 * @since 1.0.0
	 */

	public String getTaskid() {
		return taskid;
	}

	/**
	 * @param taskid
	 *            the taskid to set
	 */
	public void setTaskid(String taskid) {
		this.taskid = taskid;
	}

	/**
	 * status
	 * 
	 * @return the status
	 * @since 1.0.0
	 */

	public String getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * @param fprojectManager
	 *            the fprojectManager to set
	 */
	@Autowired
	public void setFprojectManager(FprojectManager fprojectManager) {
		this.fprojectManager = fprojectManager;
	}

	/**
	 * @param historyProjectManager
	 *            the historyProjectManager to set
	 */
	@Autowired
	public void setHistoryProjectManager(
			HistoryProjectManager historyProjectManager) {
		this.historyProjectManager = historyProjectManager;
	}

}
